import { useState, useEffect } from 'react';
import { useQuery, useMutation } from 'react-query';
import { request } from '@/request';
import { TJob, EStatus, EJobType, TFilter, TSort } from '@/types';
import { JobCard } from '@/components';
import { useScroll } from '@/hooks';
import _ from 'lodash';

const sortOption = [
   { name: 'Latest', value: TSort.latest },
   { name: 'Oldest', value: TSort.oldest },
   { name: 'Ascending', value: TSort.posAsc },
   { name: 'Descending', value: TSort.posDesc },
];

const defaultData = {
   company: '',
   status: 'ALL',
   jobType: 'ALL',
   sort: TSort.latest,
};

type TResData = {
   list: Array<TJob>;
   total: number;
};

const getSortedList = (list: Array<TJob>, sortType: TSort) => {
   switch (sortType) {
      case TSort.latest:
         return _.orderBy(list, ['createdAt'], ['desc']);
      case TSort.oldest:
         return _.orderBy(list, ['createdAt'], ['asc']);
      case TSort.posAsc:
         return _.orderBy(list, ['position'], ['asc']);
      case TSort.posDesc:
         return _.orderBy(list, ['position'], ['desc']);
      default:
         return list;
   }
};
// [data.total, page]
const JobList = () => {
   const [form, setForm] = useState<TFilter>(defaultData);
   const [page, setPage] = useState(1);

   const jobMutate = useMutation(
      (id: string) => {
         return request<TJob>(`/jobs/${id}`, {
            method: 'DELETE',
            showSuccess: true,
         });
      },
      {
         onSuccess: () => {
            setPage(1);
            refetch();
         },
      }
   );
   const { data, refetch, isLoading } = useQuery<TResData>(
      ['jobs'],
      async () => {
         const res = await request<Array<TJob>>('/jobs', {
            // params: {
            //    ...form,
            //    page,
            // },
         });

         if (page === 1) {
            getToTop();
            return res.data;
         } else {
            return {
               total: res.data.total,
               list: [...data.list, ...res.data.list],
            };
         }
      },
      {
         initialData: { list: [], total: 0 },
      }
   );

   const { ref, getToTop } = useScroll(
      {
         onScrollEnd: () => {
            if (data.total > page * 10) {
               setPage((prev) => prev + 1);
            }
         },
      },
      [data.total, page]
   );

   const handleChange = (e) => {
      const { value, name } = e.target;
      setForm({
         ...form,
         [name]: value,
      });
      if (['company', 'status', 'jobType'].includes(name)) {
         setPage(1);
      }
   };

   const handleClear = () => {
      setPage(1);
      setForm(defaultData);
   };

   const handleDelete = (id: string) => {
      jobMutate.mutate(id);
   };

   useEffect(() => {
      refetch();
   }, [page, form.company, form.status, form.jobType]);

   if (isLoading) return <div>Loading ...</div>;

   return (
      <div className="space-y-12 flex flex-col h-full">
         <div className="box w-full">
            <h2 className="font-semibold">Search From</h2>
            <div className="grid grid-cols-3 gap-x-12 mt-4 gap-y-3">
               <div className="form-item-content">
                  <label className="w-1/4">Company</label>
                  <input
                     value={form.company}
                     name="company"
                     onChange={handleChange}
                  />
               </div>
               <div className="form-item-content">
                  <label className="w-1/4">Status</label>
                  <select
                     value={form.status}
                     onChange={handleChange}
                     name="status"
                  >
                     <option value="ALL">All</option>
                     <option value={EStatus.INTERVIEW}>Interview</option>
                     <option value={EStatus.PENDING}>Pedding</option>
                     <option value={EStatus.DECLINED}>Declined</option>
                  </select>
               </div>
               <div className="form-item-content">
                  <label className="w-1/4">Type</label>
                  <select
                     value={form.jobType}
                     onChange={handleChange}
                     name="jobType"
                  >
                     <option value="ALL">All</option>
                     <option value={EJobType.FULL_TIME}>Full Time</option>
                     <option value={EJobType.PART_TIME}>Part Time</option>
                  </select>
               </div>
               <div className="form-item-content">
                  <label className="w-1/4">Sort</label>
                  <select value={form.sort} onChange={handleChange} name="sort">
                     {sortOption.map((item) => (
                        <option value={item.value} key={item.value}>
                           {item.name}
                        </option>
                     ))}
                  </select>
               </div>
               <button onClick={handleClear}>Clear Filters</button>
            </div>
         </div>
         <div className="grow overflow-hidden">
            <h2 className="font-semibold mb-2 text-xl">
               {data.total} Jobs Found
            </h2>
            <div
               className="grid grid-cols-2 gap-x-12 gap-y-4 max-h h-full overflow-auto scrollbar pb-7"
               ref={ref}
            >
               {getSortedList(data.list, form.sort).map((item) => (
                  <JobCard item={item} key={item._id} onDelete={handleDelete} />
               ))}
            </div>
         </div>
      </div>
   );
};

export default JobList;
